package com.molyfun.parents.activity.record;

import android.Manifest;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseChoosePicActivity;
import com.molyfun.parents.activity.record.adapter.RecordAdapter;
import com.molyfun.parents.rest.QiniuSDK;
import com.molyfun.parents.rest.RestClient;
import com.molyfun.parents.rest.bean.RecordResponse;
import com.molyfun.parents.rest.bean.SendRecordResponse;
import com.molyfun.parents.utils.AndroidBug5497Workaround;
import com.molyfun.parents.utils.Const;
import com.molyfun.parents.utils.FileUtils;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.view.RecordView.ChatExtendMenu;
import com.molyfun.parents.view.RecordView.ChatInputMenu;
import com.molyfun.parents.view.RecordView.VoiceRecorderView;
import com.molyfun.parents.view.footerRecycleview.DefaultFootItem;
import com.molyfun.parents.view.footerRecycleview.OnLoadMoreListener;
import com.molyfun.parents.view.footerRecycleview.RecyclerViewWithFooter;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.ButterKnife;
import butterknife.InjectView;
import mabeijianxi.camera.VCamera;
import mabeijianxi.camera.model.MediaRecorderConfig;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@RuntimePermissions
public class MineRecordActivity extends BaseChoosePicActivity implements  RecordAdapter.RecordAdapterCallback , View.OnClickListener{

    public static final int FLAG_VIDEO_REQUEST_CODE = 1010;

    protected static final String TAG = "MainTabRecordFragment";

    protected static final int REQUEST_CODE_CAMERA = 1;
    protected static final int REQUEST_CODE_LOCAL = 2;
    protected static final int REQUEST_CODE_VIDEO = 3;

    protected InputMethodManager inputManager;
    protected ClipboardManager clipboard;

    protected Handler handler = new Handler();
    @InjectView(R.id.voice_recorder)
    VoiceRecorderView voiceRecorderView;
    @InjectView(R.id.input_menu)
    ChatInputMenu inputMenu;
    @InjectView(R.id.record_list)
    RecyclerViewWithFooter mRecyclerView;
    @InjectView(R.id.title_bar_date)
    TextView mTitleBarDate;
    @InjectView(R.id.refresh)
    MaterialRefreshLayout materialRefreshLayout;
    @InjectView(R.id.base_title_left)
    ImageView mTitleLeft;
    @InjectView(R.id.base_title)
    TextView mTitle;
    @InjectView(R.id.base_title_right)
    TextView mTitleRight;

    private String mCurrentTitleBarDate;

    private LinearLayoutManager mLayoutManager;
    private RecordAdapter mRecordAdapter;

    protected int[] itemStrings = {R.string.attach_take_pic, R.string.attach_picture, R.string.attach_video};
    protected int[] itemdrawables = {R.drawable.chat_takepic_selector, R.drawable.chat_image_selector,
            R.drawable.chat_video_selector};
    static final int ITEM_TAKE_PICTURE = 1;
    static final int ITEM_PICTURE = 2;
    static final int ITEM_VIDEO = 3;
    protected int[] itemIds = {ITEM_TAKE_PICTURE, ITEM_PICTURE, ITEM_VIDEO};


    public static void startActivity(Context context){
        Intent intent = new Intent();
        intent.setClass(context, MineRecordActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_record);

        AndroidBug5497Workaround.assistActivity(this);

        ButterKnife.inject(this);

        getSupportActionBar().setTitle("");

        initView();
        mTitle.setText("日常记录");
        mTitle.getPaint().setStyle(Paint.Style.FILL_AND_STROKE);
        mTitle.getPaint().setStrokeWidth(1);

        mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setStackFromEnd(true);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecordAdapter = new RecordAdapter(this, this);
        mRecyclerView.setAdapter(mRecordAdapter);
        mTitleLeft.setOnClickListener(this);
        mTitleRight.setOnClickListener(this);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int firstVisiblePosition = mLayoutManager.findFirstVisibleItemPosition();
                if (TextUtils.isEmpty(mCurrentTitleBarDate)) {
                    mCurrentTitleBarDate = mRecordAdapter.getDateByPosition(0);
                    mTitleBarDate.setText(mCurrentTitleBarDate);
                } else {
                    String firstVisiblePositionDateStr = mRecordAdapter.getDateByPosition(firstVisiblePosition);
                    if (!TextUtils.isEmpty(firstVisiblePositionDateStr) && !firstVisiblePositionDateStr.equals(mCurrentTitleBarDate)) {
                        mCurrentTitleBarDate = firstVisiblePositionDateStr;
                        mTitleBarDate.setText(mCurrentTitleBarDate);
                    }
                }
//                System.out.println("--->Position" + firstVisiblePosition);
//                View firstView = mRecyclerView.getChildAt(0);
//                int itemHeight = firstView.getHeight();
//                System.out.println("--->itemHeight" + itemHeight);
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        mRecyclerView.setFootItem(new DefaultFootItem());
        mRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                getRecords(mRecordAdapter.getLastTimestamp(), Const.PARAM_TOPIC_BEFORE);
                //加载数据
            }
        });
//        mLayoutManager.computeVerticalScrollOffset()

//        materialRefreshLayout.setSunStyle(true);
        materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
                //refreshing...
                getRecords(mRecordAdapter.getFirstTimestamp(), Const.PARAM_TOPIC_AFTER);

            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                //load more refreshing...
                materialRefreshLayout.finishRefreshLoadMore();
            }
        });

        initVideoConfig();
        getRecords(null, null);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.base_title_left:
                finish();
                break;
            case R.id.base_title_right:
                showPopupWindow(mTitleRight);
                break;
        }
    }


    PopupWindow popupWindow;

    private void showPopupWindow(View view) {

        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.view_mine_record_popup_menu, null);
        TextView mTakeByPhone = (TextView) contentView.findViewById(R.id.take_byphone);
        TextView mLocalUpload = (TextView) contentView.findViewById(R.id.local_upload);
        mTakeByPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recordVideo(1200 * 1000);
                popupWindow.dismiss();
            }
        });
        mLocalUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RecordLocalUploadActivity.startActivity(MineRecordActivity.this);
                popupWindow.dismiss();
            }
        });

        popupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.showAsDropDown(view);

    }

    public String getAttachmentFolder() {
        return "record";
    }

    @Override
    public void onPictureUploadBegin(String path, String UploadPath) {
        RecordResponse.PlaceHolderRecordBean placeHolderRecordBean = new RecordResponse.PlaceHolderRecordBean();
        placeHolderRecordBean.setPath(path);
        placeHolderRecordBean.setState(0);
        placeHolderRecordBean.setType(1);
        placeHolderRecordBean.setCreatedatetime(System.currentTimeMillis());
        placeHolderRecordBean.setUploadPath(UploadPath);
        mRecordAdapter.addData(placeHolderRecordBean);

//        sendVideo2Server(placeHolderRecordBean);
    }

    //上传图片回调
    public void onPictureUploadSuccess(String localPath, String smallUrl, String originalUrl) {
//        System.out.println("originalUrl--->" + originalUrl);
        postRecord(localPath, 1, originalUrl, 0);
    }

    @Override
    public void onPictureUploadFailed(String path, String UploadPath) {

        RecordResponse.PlaceHolderRecordBean placeHolderRecordBean = new RecordResponse.PlaceHolderRecordBean();
        placeHolderRecordBean.setPath(path);
        placeHolderRecordBean.setState(1);
        placeHolderRecordBean.setType(1);
        placeHolderRecordBean.setUploadPath(UploadPath);
        placeHolderRecordBean.setCreatedatetime(System.currentTimeMillis());
        mRecordAdapter.updatePlaceHolderData(path, placeHolderRecordBean);

    }


    @Override
    public void onVideoUploadSuccess(String cover, String path) {

    }

    private void initVideoConfig() {
        VCamera.setVideoCachePath(FileUtils.VIDEOPATH);
        // 开启log输出,ffmpeg输出到logcat
        VCamera.setDebugMode(true);
        // 初始化拍摄SDK，必须
        VCamera.initialize(this);
    }

    private void getRecords(String pagetimestamp, final String around) {
//        showProgressDialog();
        Call<RecordResponse> call = MFPApplication.getInstance().getRestClient().getRecordList(RestClient.DEFAULT_PAGE, RestClient.DEFAULT_PAGE_SIZE, pagetimestamp, around);
        call.enqueue(new Callback<RecordResponse>() {
            @Override
            public void onResponse(Call<RecordResponse> call, Response<RecordResponse> response) {
//                dismissProgressDialog();
                if (response.body() != null && response.body().getData() != null && response.body().getData().getRecords() != null) {
                    if (TextUtils.isEmpty(around)) {
                        mRecordAdapter.refreshData(response.body().getData().getRecords());
                    } else {
                        if (around.equals(Const.PARAM_TOPIC_BEFORE)) {
                            mRecordAdapter.addAll(response.body().getData().getRecords());
                            if (response.body().getData().getRecords().size() < RestClient.DEFAULT_PAGE_SIZE) {
                                mRecyclerView.setEnd();
                            }
                        } else {
                            mRecordAdapter.addAllHeader(response.body().getData().getRecords());
                        }
                    }
                    if (!TextUtils.isEmpty(around)) {
                        if (around.equals(Const.PARAM_TOPIC_BEFORE)) {

                        } else {
                            materialRefreshLayout.finishRefresh();
                        }
                    }

                }
            }

            @Override
            public void onFailure(Call<RecordResponse> call, Throwable t) {
//                dismissProgressDialog();
                if (!TextUtils.isEmpty(around)) {
                    if (around.equals(Const.PARAM_TOPIC_BEFORE)) {

                    } else {
                        materialRefreshLayout.finishRefresh();
                    }
                }
            }
        });
    }

    @NeedsPermission(Manifest.permission.RECORD_AUDIO)
    void onRecordBtnPress() {
        //DO NOTHING
    }

    void doACacheNeedsPermission() {
        //处理当用户允许该权限时需要处理的方法
    }

    @OnShowRationale(Manifest.permission.RECORD_AUDIO)
    void ACacheShowRationale(PermissionRequest request) {
        request.proceed(); // 提示用户权限使用的对话框
    }

    @OnNeverAskAgain(Manifest.permission.RECORD_AUDIO)
    void ACacheOnNeverAskAgain() {
        toast("拒绝了语音权限");
    }

    /**
     * 如果用户拒绝该权限执行的方法
     */
    @OnPermissionDenied(Manifest.permission.RECORD_AUDIO)
    void ACacheOnPermissionDenied() {
        toast("拒绝了语音权限");
    }

    /**
     * 权限请求回调，提示用户之后，用户点击“允许”或者“拒绝”之后调用此方法
     *
     * @param requestCode  定义的权限编码
     * @param permissions  权限名称
     * @param grantResults 允许/拒绝
     */
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        MainTabRecordFragment.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    private void initView() {
        if (PreferencesStorageUtil.isUserEnter(this)) {


            inputMenu.init();
            inputMenu.setChatInputMenuListener(new ChatInputMenu.ChatInputMenuListener() {

                @Override
                public void onSendMessage(String content) {
//                sendTextMessage(content);
                    postRecord(content, 4, null, 0);
                }

                //            @NeedsPermission(Manifest.permission.RECORD_AUDIO)
                @Override
                public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
                    onRecordBtnPress();

                    return voiceRecorderView.onPressToSpeakBtnTouch(v, event, new VoiceRecorderView.VoiceRecorderCallback() {

                        @Override
                        public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                            sendVoiceMessage(voiceFilePath, voiceTimeLength);
                        }
                    });
                }
            });
            registerExtendMenuItem();
            inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        }
    }

    private void sendVoiceMessage(final String voiceFilePath, final int voiceTimeLength) {
        //添加到列表，上传到服务器,列表loading
        MFPApplication.getInstance().getQiniuSDK().uploadFile(voiceFilePath, "mfp/voice" + "/voice_" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".mp3"
                , new QiniuSDK.OnFileUpLoadCallback() {
                    @Override
                    public void onFileUpload(String url) {
                        //发送到自己服务器
                        postRecord(null, 3, url, voiceTimeLength);
                    }

                    @Override
                    public void onFileUploadFailed(String path, String UploadPath) {

                    }

                });

    }

    private void postRecord(final String content, final int type, final String url, final int timelen) {
        postRecord(content, type, url, null, timelen);
    }

    /**
     * @param content  文字内容
     * @param type     1:图片 2:视频 3:音频 4:文字
     * @param url      音频、视频路径
     * @param coverUrl 视频cover url
     * @param timelen  时长
     */
    private void postRecord(final String content, final int type, final String url, final String coverUrl, final int timelen) {
        Call<SendRecordResponse> call = MFPApplication.getInstance().getRestClient().postRecord(content, type, url, coverUrl, timelen);
        call.enqueue(new Callback<SendRecordResponse>() {
            @Override
            public void onResponse(Call<SendRecordResponse> call, Response<SendRecordResponse> response) {
                dismissProgressDialog();
                RecordResponse.RecordBean recordBean = response.body().getData();
                if(type == 2 || type == 1){
                    mRecordAdapter.updatePlaceHolderData(content, recordBean);
                }else{
                    mRecordAdapter.addData(recordBean);
                }
                if(response.body().getCode() == 200){
                    toast("发送成功");
                }
            }

            @Override
            public void onFailure(Call<SendRecordResponse> call, Throwable t) {

                if(type == 2 || type == 1) {
                    RecordResponse.PlaceHolderRecordBean placeHolderRecordBean = new RecordResponse.PlaceHolderRecordBean();
                    placeHolderRecordBean.setPath(content);
                    placeHolderRecordBean.setState(1);
                    placeHolderRecordBean.setType(type);
                    if(type == 2){
                        placeHolderRecordBean.setUploadPath("mfp/video" + "/video_" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".mp4");//placeHolderRecordBean.getUploadPath());
                    }else{

                        placeHolderRecordBean.setUploadPath(getAttachmentFolder() + "/ic_" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".jpg");//placeHolderRecordBean.getUploadPath());
                    }
                    placeHolderRecordBean.setCreatedatetime(System.currentTimeMillis());
                    mRecordAdapter.updatePlaceHolderData(content, placeHolderRecordBean);
                }

                dismissProgressDialog();
            }
        });
    }

    /**
     * register extend menu, item id need > 3 if you override this method and keep exist item
     */
    protected void registerExtendMenuItem() {
        for (int i = 0; i < itemStrings.length; i++) {
            inputMenu.registerExtendMenuItem(itemStrings[i], itemdrawables[i], itemIds[i], new MyItemClickListener());
        }
    }

    /**
     * handle the click event for extend menu
     */
    class MyItemClickListener implements ChatExtendMenu.ChatExtendMenuItemClickListener {

        @Override
        public void onClick(int itemId, View view) {
            switch (itemId) {
                case ITEM_TAKE_PICTURE:
                    takePicture();
                    break;
                case ITEM_PICTURE:
                    choosePicture();
                    break;
                case ITEM_VIDEO:
                    recordVideo();
//                    startActivity(new Intent(getActivity(), VideoRecordActivity.class));
                    break;

                default:
                    break;
            }
        }

    }

    /**
     * 容错，防止多次调用
     */
    private String mLastUploadVideoPath;

    @Override
    protected void sendVideo2Server(final String videoPath) {
        showProgressDialog("退出页面将取消视频上传");
        if (!TextUtils.isEmpty(mLastUploadVideoPath)) {
            if (mLastUploadVideoPath.equals(videoPath)) {
                dismissProgressDialog();
                return;
            }
        }
        mLastUploadVideoPath = videoPath;

        RecordResponse.PlaceHolderRecordBean placeHolderRecordBean = new RecordResponse.PlaceHolderRecordBean();
        placeHolderRecordBean.setPath(videoPath);
        placeHolderRecordBean.setType(2);
        placeHolderRecordBean.setState(0);
        placeHolderRecordBean.setCreatedatetime(System.currentTimeMillis());
        placeHolderRecordBean.setUploadPath("mfp/video" + "/video_" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".mp4");
        mRecordAdapter.addData(placeHolderRecordBean);

        sendVideo2Server(placeHolderRecordBean);

    }

    private void sendVideo2Server(final RecordResponse.PlaceHolderRecordBean placeHolderRecordBean){
        MFPApplication.getInstance().getQiniuSDK().uploadFile(placeHolderRecordBean.getPath(), placeHolderRecordBean.getUploadPath()
                , new QiniuSDK.OnFileUpLoadCallback() {
                    @Override
                    public void onFileUpload(String videoUrl) {
                        dismissProgressDialog();
                        //发送到自己服务器
                        postRecord(placeHolderRecordBean.getPath(), 2, videoUrl, videoUrl + "?vframe/png/offset/0/w/480/h/480", 0);
                    }

                    @Override
                    public void onFileUploadFailed(String path, String UploadPath) {
                        dismissProgressDialog();
                        mLastUploadVideoPath = null;
//                        RecordResponse.PlaceHolderRecordBean placeHolderRecordBean = new RecordResponse.PlaceHolderRecordBean();
                        placeHolderRecordBean.setPath(path);
                        placeHolderRecordBean.setState(1);
                        placeHolderRecordBean.setType(2);
//                        placeHolderRecordBean.setUploadPath(placeHolderRecordBean.getUploadPath());
                        placeHolderRecordBean.setCreatedatetime(System.currentTimeMillis());
                        mRecordAdapter.updatePlaceHolderData(path, placeHolderRecordBean);
                    }
                });
//                    }
//                });
//            }
//        }).run();
    }

    /**
     * 得到根Fragment
     *
     * @return
     */
//    private Fragment getRootFragment() {
//        Fragment fragment = getParentFragment();
//        while (fragment.getParentFragment() != null) {
//            fragment = fragment.getParentFragment();
//        }
//        return fragment;
//
//    }

    public void recordVideo(){
        recordVideo(60 * 1000);
    }

    public void recordVideo(int maxTime) {
        MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
                .doH264Compress(true)
                .smallVideoWidth(480)
                .smallVideoHeight(480)
                .recordTimeMax(maxTime)
                .maxFrameRate(20)
                .minFrameRate(8)
                .captureThumbnailsTime(1)
                .recordTimeMin((int) (1.5 * 1000))
                .build();

        startActivityForResult(new Intent(this, MediaRecorderActivity.class).putExtra(MediaRecorderActivity.MEDIA_RECORDER_CONFIG_KEY, config), FLAG_VIDEO_REQUEST_CODE);
//        MediaRecorderActivity.goSmallVideoRecorder(getActivity(), config, FLAG_VIDEO_REQUEST_CODE);
    }

    @Override
    public void onRecordReupload(RecordResponse.RecordBean recordBean) {
        RecordResponse.PlaceHolderRecordBean placeHolderRecordBean = (RecordResponse.PlaceHolderRecordBean)recordBean;
        System.out.println("onRecordReupload-placeHolderRecordBean.getContent()-->" + recordBean.getContent() +
        " placeHolderRecordBean.getUrl--->" + recordBean.getUrl() + " placeHolderRecordBean.getPath()--->" + placeHolderRecordBean.getPath()
         + " placeHolderRecordBean.getUploadPath--->" + placeHolderRecordBean.getUploadPath());
        if(recordBean.getType() == 1){
            //图片

            sendPlaceHolderRecord(placeHolderRecordBean);
            placeHolderRecordBean.setPath(placeHolderRecordBean.getPath());
//            placeHolderRecordBean.setUploadPath(placeHolderRecordBean.getUploadPath());
            placeHolderRecordBean.setState(0);
            placeHolderRecordBean.setType(1);
            placeHolderRecordBean.setCreatedatetime(System.currentTimeMillis());
            mRecordAdapter.updatePlaceHolderData(placeHolderRecordBean.getPath(), placeHolderRecordBean);

        }else if(recordBean.getType() == 2){
            //视频
            sendVideo2Server(placeHolderRecordBean);
            placeHolderRecordBean.setPath(placeHolderRecordBean.getPath());
//            placeHolderRecordBean.setUploadPath(placeHolderRecordBean.getUploadPath());
            placeHolderRecordBean.setState(0);
            placeHolderRecordBean.setType(2);
            placeHolderRecordBean.setCreatedatetime(System.currentTimeMillis());
            mRecordAdapter.updatePlaceHolderData(placeHolderRecordBean.getPath(), placeHolderRecordBean);
        }
    }
}
